package com.sz.web.model;

import com.sz.framework.trace.SzTraceIdDetector;
import com.sz.web.context.SzWebContext;
import com.sz.web.context.SzWebContextHolder;
import lombok.Data;

import java.util.UUID;

/**
 * 统一响应封装
 *
 * @author: yxl
 * 2025-07-23
 */
@Data
public class ApiResponse<T> {
    private int code;
    private String message;
    private T data;
    private long timestamp;
    private String traceId;

    // 私有构造方法
    private ApiResponse(int code, String message, T data, String traceId) {
        this.code = code;
        this.message = message;
        this.data = data;
        this.traceId = traceId;
        this.timestamp = System.currentTimeMillis();
    }

    // 成功响应（静态工厂方法）
    public static <T> ApiResponse<T> success(T data) {
        return new ApiResponse<>(200, "success", data, getCurrentTraceId());
    }

    // 失败响应（静态工厂方法）
    public static <T> ApiResponse<T> fail(int code, String message) {
        return new ApiResponse<>(code, message, null, getCurrentTraceId());
    }

    // 获取当前请求的TraceId
    private static String getCurrentTraceId() {
        SzWebContext context = SzWebContextHolder.current();
        if (context != null) {
            return SzWebContextHolder.getTraceId();
        }
        return null;
    }

}
